import config from "@/utils/config"
import { user_info, login } from '@/api/login'
import { getStorage, setStorage, removeStorage } from '@/utils/storage';
const state = {
	token: getStorage(config.api.tokenField) ? getStorage(config.api.tokenField) : null,
	user: getStorage('user-info') ? JSON.parse(getStorage('user-info')) : {},
	letterUser:{}
}
const mutations = {
	CACHE_TOKEN: (state, data) => {
		state.token = data
		setStorage(config.api.tokenField, data, 129600000)
	},
	CACHE_USER: (state, data) => {
		state.user = data
		setStorage('user-info', JSON.stringify(data), 129600000)
	},
	SIGN_OUT: (state, data) => {
		state.user = {}
		state.token = null
		removeStorage(config.api.tokenField)
		removeStorage('user-info')
	},
	LETTER_USER: (state, data) => {
		state.letterUser = data
	},
	DECREMENT_BALANCE: (state, data) => {
		if (data.type == 'withdraw_balance') {
			state.user.withdraw_balance -= data.money
		} else {
			state.user.balance -= data.money
		}
		setStorage('user-info', JSON.stringify(state.user), 129600000)
	},
	INCREMENT_BALANCE: (state, data) => {
		state.user.balance += data.money
		setStorage('user-info', JSON.stringify(state.user), 129600000)
	},

}
const actions = {
	cacheToken ({ commit, state }, data) {
		state.token = data
		return new Promise((resolve, reject) => {
			user_info().then(response => {
				commit('CACHE_USER', response);
				commit('CACHE_TOKEN', data);
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	login ({ commit, state }, data) {
		return new Promise((resolve, reject) => {
			login(data).then(response => {
				commit('CACHE_TOKEN', response.access_token)
				commit('CACHE_USER', response.info)
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	updateInfo ({ commit, state }, data) {
		commit('CACHE_USER', data)
	},
	decrementBalance ({ commit, state }, data) {
		commit('DECREMENT_BALANCE', data)
	},
	incrementBalance ({ commit, state }, data) {
		commit('INCREMENT_BALANCE', data)
	},
	signOut ({ commit }) {
		commit('SIGN_OUT')
	},
	setLetterUser ({ commit, state }, data) {
		commit('LETTER_USER', data)
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
